<template>
  <section>
    <!--工具条：高级查询，上下架-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true" :model="searchForm">
        <el-form-item>
          <el-input v-model="searchForm.keyword" placeholder="宠物名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="getPets">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>

    <!--列表展示-->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="名称" >
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" >
      </el-table-column>
      <el-table-column prop="costprice" label="成本价"  >
      </el-table-column>
      <el-table-column prop="state" label="状态"  >
        <template scope="scope" >
          <span v-if="scope.row.state==0" style="color: red">下架</span>
          <span v-if="scope.row.state!=0" style="color: green">上架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间"  >
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间"  >
      </el-table-column>
      <el-table-column prop="shop.name" label="店铺"  >
      </el-table-column>
      <el-table-column prop="type.name" label="品种"  >
      </el-table-column>
      <el-table-column prop="user.username" label="用户"  >
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条：批量删除，分页-->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改的模态框-->
    <el-dialog :title="title"  :visible.sync="editFormVisible" @close="formClose">
      <el-form :model="editForm" label-width="80px" :rules="editFormRules" ref="editForm">
        <el-form-item label="名称" prop="name">
          <el-input v-model="editForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="editForm.saleprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="editForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="editForm.costprice" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="支付方式">
          <el-select v-model="editForm.payType" value-key="value" placeholder="请选择">
            <el-option
                    v-for="item in payTypes"
                    :label="item.label"
                    :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="宠物类型">
          <!--
            el-select：选择框
              clearable： 可清理
              value-key="id" - 如果传递的是一个对象，这个属性值必须
            el-option：选项 - 需要遍历 所以用v-for
              v-for="item in types" : 遍历所有的类型
              :key="item.id"： 指定key值，没什么用
              :label="item.name" ： 指定要显示哪一个属性的值
              :value="item.id"：指定要传递那个值
            回显机制：
              <el-option>中：value的值与<el-select>的 v-model值匹配：
              可以是对象，必须在<el-select>中加value-key属性【value-key="id"】
                表明回显数据的依据，因为对象中有很多字段，根据对象中的id进行回显
              也可以是id【常用 - 简单】
          -->
          <el-select v-model="editForm.type"  value-key="id" clearable placeholder="请选择">
            <el-option v-for="item in types"
                       :label="item.name"
                       :value="item">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="资源" prop="resources">
          <el-upload
              class="upload-demo"
              action="http://localhost:8888/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="简介" >
          <quill-editor v-model="editForm.detail.intro" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor v-model="editForm.detail.adoptNotice" :options="quillOption">
          </quill-editor>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="formClose">取消</el-button>
        <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
//引入富文本编辑器
import { quillEditor } from "vue-quill-editor";
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import routes from "../../../src/routes";

//富文本与fastDfs集成
import quillConfig from '../../../src/common/js/quill-config.js'
import {getPetListByConditon, petOffSale, petOnSale, getPetType, petEdit, getPetDetail, shopLogoDelete,batchRemovePet, petDeleteById} from "../../../src/api/api";

export default {
  components: {
    quillEditor //使用富文本编辑器<quill-editor>
  },
  data() {
    return {
      //富文本集成fastDfs数据
      quillOption: quillConfig,
      //文件上传列表 - 资源resources
      fileList:[],

      //添加和修改模态框的标题
      title:'',

      //高级查询数据
      searchForm: {
        keyword: null
      },
      //分页查询数据
      pets: [], //分页查询列表数据
      //分页查询 - 总数量
      totals: 0,
      //分页查询 - 当前页
      pageSize: 5,
      //分页查询 - 每页显示的条数
      currentPage: 1,
      listLoading: false, //分页查询 - 列表忙等框
      payTypes:[
        {
          value: 0,
          label: '垫付'
        },
        {
          value: 1,
          label: '余额支付'
        },{
          value: 2,
          label: '银行转账'
        }
      ],
      //批量删除
      sels: [],//列表选中列

      //添加和修改模态框数据1
      editFormVisible: false,//模态框是否显示
      editLoading: false, //忙等框
      editFormRules: { //模态框验证规则
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' }
        ]
      },
      //添加和修改模态框数据2
      editForm: {
        id: null,
        name: null,
        costprice: 0,
        saleprice: 0,
        resources:null,
        //上下架时间：添加时默认为null，上架和下架时才单独修改
        //offsaletime:null,
        //onsaletime:null,
        //createtime创建时间：添加的时候要添加-默认值，创建时间不做修改
        //createtime:null,
        //添加的时候可以选，也可以修改
        type_id: null,
        //以下三个添加的时候：管理员添加不是来自于寻主消息都为null - 默认值
        //以下三个修改的时候：不能修改
        //shop_id: null,
        //user_id: null,
        //search_master_msg_id: null,
        detail:{
          id : null,
          intro:null,
          adoptNotice:null
        },
        payType: {
          value: 0
        }
      },
      //加载所有的宠物类型
      types:[],
      deletePicList:[]
    }
  },
  methods: {

    //上架
    onsale(){
      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾上架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认上架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        petOnSale(ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '上架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        });
      }).catch(() => {

      });
    },

    //下架
    offsale(){

      var ids = this.sels.map(item => item.id);
      //获取选中的行
      if(!this.sels || this.sels.length  <1){
        this.$message({ message: '老铁，你不选中数据，臣妾下架不了啊....',type: 'error'});
        return;
      }
      this.$confirm('确认下架选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        petOffSale(ids).then((res) => {
          this.listLoading = false;

          if(res.data.success){
            this.$message({
              message: '下架成功',
              type: 'success'
            });
          }else{
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
          this.getPets();
        });
      }).catch(() => {

      });
    },

    //资源图片上传成功之后的处理
    handleSuccess(response, file, fileList) {
      // console.log("===========")
      // console.log(fileList);
      //resultObj 文件的服务器地址，放到数据库中
      //根据双向绑定 logo 就有值 1,2,3
      let resourcesTmp = '';
      if(fileList!=null && fileList.length>0){
        for(var i=0;i<fileList.length;i++){
          if(i==0){
            if (fileList[i].response) {
              resourcesTmp = resourcesTmp+fileList[i].response.data;
            } else {
              let url = fileList[i].url;
              url = url.substring(url.indexOf("/group1"));
              resourcesTmp = resourcesTmp + url;
            }

          }else{
            if (fileList[i].response) {
              resourcesTmp = resourcesTmp+","+fileList[i].response.data;

            } else {
              let url = fileList[i].url;
              url = url.substring(url.indexOf("/group1"));
              resourcesTmp = resourcesTmp +","+ url;
            }
          }
        }
      }
      this.editForm.resources = resourcesTmp;
    },
    formClose() {
      this.deletePicList = '';
      this.editFormVisible = false;
    } ,


    //资源图片点击删除时的处理
    handleRemove(file, fileList) {
      // 初始化变量，存储当前图片的地址
      var resourcesTmp = '';
      if(fileList!=null && fileList.length>0){
        for(var i=0;i<fileList.length;i++){
            if (i == 0 ) {
              if (fileList.response) {
                resourcesTmp = fileList[i].response.data
              } else {
                let url = fileList[i].url;
                url = url.substring(url.indexOf("/group1"));
                resourcesTmp = url;
              }
            } else {
              if (fileList.response) {
                resourcesTmp = resourcesTmp + "," +fileList[i].response.data
              } else {
                let url = fileList[i].url;
                url = url.substring(url.indexOf("/group1"));
                resourcesTmp = resourcesTmp + "," + url;
              }
            }
        }
      };
      // 获取 当前存储当前 会被删除的图片的集合
      var mylist = this.deletePicList;
      if(mylist.length == 0){
        if (file.response) {
          mylist = mylist + file.response.data;
        } else {
          let url = file.url;
          url = url.substring(url.indexOf("/group1"));
          mylist = mylist + url;
        }
      }else{
        if (file.response) {
          mylist = mylist + "," + file.response.data;
        } else {
          let url = file.url;
          url = url.substring(url.indexOf("/group1"));
          mylist = mylist + "," + url;
        }
      };
      // 复制给当前列表
      this.editForm.resources = resourcesTmp;
      this.deletePicList = mylist;
      console.log("剩余列表 ：" +  resourcesTmp);
      console.log("删除列表 ：" + mylist)


    },

    //点击某一页的处理
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },

    // 删除时，判断是否时最后一页的唯一一条
    countPageSize(index) {
      let cPage = this.currentPage;
      let pSize = this.pageSize;
      let total = this.totals;
      // 计算是否是最后一条
      if ( (cPage - 1) * pSize + index == total - 1  && index == 0) {
        this.queryParams.currentPage  = this.queryParams.currentPage - 1;
      }
    },
    //高级查询 + 分页查询
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        keyword:this.searchForm.keyword
      };
      //显示列表忙等框
      this.listLoading = true;
      //发送异步请求加载列表数据
      getPetListByConditon(para).then(res=>{
        this.pets=res.data.data;
        this.totals=res.data.totals;
        //关闭列表忙等框
        this.listLoading = false;
      });
    },

    //删除
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => { // 点击确认后执行
        //显示列表忙等框
        this.listLoading = true;
        //后台地址的请求
        petDeleteById(row.id).then((res) => {
          //成功不成功都要让盲等框消失
          this.listLoading = false;
          if(res.data.success){//删除成功
            this.countPageSize(); // 判断删除时，是否时最后一页唯一一条
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.getPets();
          }else{
            //后台500错误，显示具体错误信息
            this.$message.error(res.data.message);
          }
        }).catch(res => {
          //主要是针对连接不上服务器啊，前端发送问题等
          this.$message.error("系统错误，请稍后重试!");
        })
      }).catch(() => {
      });
    },

    //批量获取被删除对象的id
    selsChange: function (sels) {
      this.sels = sels;
    },

    //批量删除 - 批量删除逻辑处理
    batchRemove: function () {
      //获取被删除对象的id组成的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认删除选中记录吗？', '温馨提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        batchRemovePet(ids).then(res=>{
          if(res.data.success){
            this.listLoading = false;
            this.$message({
              message: '删除成功',
              type: 'success'
            });
            this.currentPage = 1;
            this.getPets();
          }else{
            this.listLoading = false;
            this.$message({
              message: res.data.message,
              type: 'error'
            });
          }
        }).catch(res=>{
          //主要是针对连接不上服务器啊，前端发送问题等
          this.$message.error("系统错误，请稍后重试!");
        })

      }).catch(() => {
      });
    },

    //点击编辑按钮弹出模态框
    handleEdit: function (index, row) {
      //进行数据回显：将row【本省就是一个json对象  克隆 给一个空对象{}】,防止引用传递导致的数据变化
      this.editForm = Object.assign({}, row);
      //加载所有的宠物类型
      this.getTypes();
      //会显示详情
      getPetDetail(row.id).then(result=>{
        this.editForm.detail = result.data;
      });
      //图片回显
      this.fileList = [];
      var resources =  row.resources;
      if(resources){
        var resourcesArr = resources.split(",");
        for(var i=0;i<resourcesArr.length;i++){
          this.fileList.push({url:"http://47.95.117.210:8888"+resourcesArr[i]})
          // this.fileList.push({response : {data : resourcesArr[i]}})
        }
      }
      // console.log("====================================================")

      this.title = "编辑";
      this.editFormVisible = true;
    },

    //显示新增界面
    handleAdd: function () {
      //初始化表单字段-利用的双向绑定的特性
      this.editForm = {
        id: null,
        name: null,
        costprice: 0,
        saleprice: 0,
        //resources:null,
        //添加的时候可以选，也可以修改
        type_id: null,
        detail:{
          intro:null,
          adoptNotice:null
        }
      }

      //清空图片列表
      this.fileList = [];
      //加载所有的宠物类型
      this.getTypes();
      this.title='新增';
      //打开弹出框
      this.editFormVisible = true;
    },

    //编辑
    editSubmit: function () {
      //验证当前的表单是否符合验证规则
      this.$refs.editForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //显示提交按钮忙等框
            this.editLoading = true;
            //把表单的数据组装为json
            let para = Object.assign({}, this.editForm);
            var mylist = this.deletePicList;
            if (mylist.length > 0) {
              for (let i = 0; i < mylist.length; i++) {
                shopLogoDelete(mylist[i]).then().catch();
              }
            }
            petEdit(para).then((res) => {
              if(res.data.success){
                this.editLoading = false;
                this.$message({
                  message: '提交成功',
                  type: 'success'
                });
                //重置表单-调用现成的方法
                this.$refs['editForm'].resetFields();
                //关闭 加载框
                this.editFormVisible = false;
                //重新刷新页面数据
                this.getPets();
              }else{
                this.editLoading = false;  		//忙等框不显示
                this.editFormVisible = false; 	//隐藏对话框
                this.$message({
                  message: res.data.message,
                  type: 'error'
                });
              }
            }).catch(res => {
              alert("系统错误,请稍后重试");
            })
          });
        }
      });
    },

    //获取所有的宠物类型
    getTypes(){
      getPetType().then(result=>{
        this.types = result.data;
      })
    }

  },
  mounted() {
    //当页面加载完以后。执行的方法
    this.getPets();
  }
}

</script>

<style scoped>

</style>